<?php
/**
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2020/1/10
 * Time: 15:07
 */

namespace app\im\model;

use think\facade\Cache;
use think\Model;

class ImBase extends Model
{

    protected $autoWriteTimestamp = 'datetime';

    // 时间格式化
    public function getCreateTimeAttr($value)
    {
        return $value ? format_date($value) : "";
    }

    // 时间格式化
    public function getUpdateTimeAttr($value)
    {
        return $value ? format_date($value) : "";
    }

    // 通用列表查询
    // 解决分页查询新数据冲突
    public function scopeLists($query, $params)
    {
        $where = [];
        $page = $params["page"] ?? 1;
        $limit = $params["limit"] ?? 10;
        $user_id = $params["user_id"] ?? null;

        $cache_name = 'select:history:' . $user_id;
        if ($page <= 1) {
            // 查询时间
            $select_time = date("Y-m-d H:i:s");
            Cache::set($cache_name, $select_time, 3600);
        } else {
            $where[] = ['create_time', '< time', Cache::get($cache_name)];
        }

        $query->where($where)->order("id desc")
            ->page($page)->limit($limit);
    }

    // 通过ID获取字段值
    public static function getValueByID($id, $field)
    {
        return self::where(compact('id'))
            ->value($field);
    }

    public static function setValueById($id, $field, $value)
    {
        return self::where(compact('id'))
            ->setField($field, $value);
    }
}